package com.party.jackclientandroid;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.party.jackclientandroid.bean.ImageBean;
import com.party.jackclientandroid.controller.ChoosePictureController;
import com.party.jackclientandroid.event.AMapBeanEvent;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.okhttp.RxSchedulers;
import com.party.jackclientandroid.photoselector.PictureDetailActivity;
import com.party.jackclientandroid.utils.ConstUtils;
import com.party.jackclientandroid.utils.ToastUtils;
import com.party.jackclientandroid.view.dialog.AlertProgressDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;

public abstract class BaseActivity extends AppCompatActivity {

    protected MApplication mApplication;
    protected BaseActivity mActivity;
    protected String mClassName;
    protected Resources mResources;
    public Unbinder unbinder;
    public LoadViewHelper helper;
    //当前activity 是否在显示状态
    public boolean mActivityIsShow = false;

    protected CompositeDisposable compositeDisposable;
    protected AlertDialog mProgressDialog;

    protected ChoosePictureController choosePictureController;

    public MApplication getmApplication() {
        return (MApplication) getApplication();
    }

    @Override
    public void setContentView(int layoutResID) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//禁止横竖屏转换
        mActivityIsShow = true;
        super.setContentView(layoutResID);
        bindButterKnife();
        init();
    }

    public void initErrorView(View view) {
        helper = new LoadViewHelper(view);
    }

    public void setTitle(String title) {
        TextView viewById = findViewById(R.id.tv_title);
        viewById.setText(title);
    }


    protected void init() {
        mActivity = this;
        choosePictureController = new ChoosePictureController(this);
        mApplication = (MApplication) getApplication();
        mClassName = getClass().getSimpleName();
        mResources = getResources();
        ((MApplication) getApplication()).pushActivity(this);
        initBack();
    }

    protected void initBack() {
        View viewById = findViewById(R.id.iv_back);
        if (viewById != null) {
            viewById.setOnClickListener((View v) -> {
                finish();
            });
        }
    }

    public void localComplete(AMapBeanEvent aMapBeanEvent) {

    }


    long firstTime;

    /**
     * 等待时间为 2秒
     *
     * @return
     */
    public boolean dupCommit() {
        return dupCommit(2000);
    }

    /**
     * 防重复提交
     *
     * @param waitTime 等待时间
     * @return
     */
    public boolean dupCommit(long waitTime) {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > waitTime) {
            firstTime = secondTime;
            return false;
        }
        showToast("手速太快了");
        return true;
    }


    protected void bindButterKnife() {
        try {
            unbinder = ButterKnife.bind(this);
        } catch (Exception e) {
        }
    }

    private CompositeDisposable getCompositeDisposable() {
        if (compositeDisposable == null) {
            synchronized (this) {
                if (compositeDisposable == null) {
                    compositeDisposable = new CompositeDisposable();
                }
            }
        }
        return compositeDisposable;
    }

    /**
     * 添加一个请求,子线程中执行然后切换回主线程
     *
     * @param observable
     */
    public <T> void addDisposableIoMain(Observable<T> observable, Consumer<T> consumer) {
        CompositeDisposable compositeDisposable = getCompositeDisposable();
        Consumer<Throwable> throwable = (Throwable temp) -> {
            hideAlertDialog();
            showToast(temp.getMessage());
        };

        if (observable != null) {
            Observable<T> observableCompose = observable.compose(RxSchedulers.io_main());
            compositeDisposable.add(observableCompose.subscribe(consumer, throwable));
        }
    }


    /**
     * 添加一个请求,子线程中执行然后切换回主线程
     *
     * @param observable
     */
    public <T> void addDisposableIoMain(Observable<T> observable, Consumer<T> consumer, Consumer<Throwable> throwable) {
        CompositeDisposable compositeDisposable = getCompositeDisposable();
        if (observable != null) {
            Observable<T> observableCompose = observable.compose(RxSchedulers.io_main());
            compositeDisposable.add(observableCompose.subscribe(consumer, throwable));
        }
    }

    /**
     * 结束所有请求
     */
    private void removeCompositeDisposable() {
        if (compositeDisposable != null) {
            compositeDisposable.clear();
            compositeDisposable = null;
        }
    }

    @Override
    protected void onPause() {
        mActivityIsShow = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unbinder != null) unbinder.unbind();
        mApplication.removeActivity(this);
        removeCompositeDisposable();
    }

    /**
     * 隐藏软键盘
     *
     * @param context
     * @param view
     */
    public void hideSoftInput(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && softInputIsOpen(context)) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * @param context
     * @return 若返回true，则表示输入法打开
     */
    public boolean softInputIsOpen(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        return imm.isActive();
    }

    /**
     * 显示进度框
     */
    public void showLoadingDialog() {
        showLoadingDialog(getResources().getString(R.string.commit_data_ing));
    }

    /**
     * 显示进度框
     */
    public void showLoadingDialog(String str) {
        if (mProgressDialog == null) {
            mProgressDialog = new AlertProgressDialog.Builder(mActivity)
                    .setView(R.layout.layout_alert_dialog)
                    .setCancelable(false)
                    .setMessage(str)
                    .show();
        } else {
            mProgressDialog.show();
        }
    }

    /**
     * 隐藏进度框
     */
    public void hideAlertDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (choosePictureController != null) {
            choosePictureController.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void showToast(String message) {
        ToastUtils.t(mApplication, message);
    }

    /**
     * 选择完照片之后或者查看大图完之后更新数据到UI界面,请在包含gridLayout控件的界面重写此方法
     *
     * @param list
     */
    public void updateChoosePictures(List<ImageBean> list) {

    }

    /**
     * 如果原始有数据,比如编辑的时候
     *
     * @return
     */
    public List<ImageBean> getOriginDataList() {
        return null;
    }

    /**
     * 用户点击查看大图或者是添加图片调用
     *
     * @param event
     */
//    public void onClickImageEvent( event) {
//        if (mApplication.getTopActivity() != mActivity) return;
//        if (event.itemPosition == -1 || TextUtils.isEmpty(event.url)) {
//            if (choosePictureController != null) {
//                choosePictureController.checkCameraPermissions();
//            }
//            return;
//        }
//        int position = event.position;
//        ArrayList<ImageBean> urlList = event.urlList;
//        int size = urlList.size();
//        int index = -1;
//        for (int i = 0; i < size; i++) {
//            if (urlList.get(i).getImgPath().equals("")) {
//                index = i;
//                break;
//            }
//        }
//        if (index != -1) {
//            urlList.remove(index);
//        }
//        if (urlList.size() == 0) return;
//        Intent intent = new Intent(mActivity, PictureDetailActivity.class);
//        intent.putExtra("currentItem", position);
//        intent.putExtra("dataList", urlList);
//        intent.putExtra("deleteFlag", canAddPictures());
//        startActivityForResult(intent, ConstUtils.IMAGE_DETAIL_CODE);
//    }

    /**
     * 基本参数的容器
     *
     * @return
     */
    public HashMap<String, String> getTokenMap() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("token", mApplication.getToken());
        return hashMap;
    }

    /**
     * 判断用户是否登录过
     *
     * @return
     */
    public boolean isLogin() {
        if (!TextUtils.isEmpty(mApplication.getToken())) {
            return true;
        }
        return false;
    }

    public void startActivity(Class clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    public void startActivity(Class clazz, String key, String value) {
        Intent intent = new Intent(this, clazz);
        intent.putExtra(key, value);
        startActivity(intent);
    }

    public void startActivity(Class clazz, Intent intent) {
        intent.setClass(this, clazz);
        startActivity(intent);
    }

    /**
     * 跳转去登录
     */
    public void handleToLogin() {
        Intent intent = new Intent(mActivity, LoginActivity.class);
        startActivity(intent);
    }

    public void showPicture(boolean isAdded, int position1, int position, String url, ArrayList<ImageBean> urlList) {
        int size = urlList.size();
        int index = -1;
        for (int i = 0; i < size; i++) {
            if (urlList.get(i).getImgPath().equals("")) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            urlList.remove(index);
        }
        if (urlList.size() == 0) return;
        Intent intent = new Intent(this, PictureDetailActivity.class);
        intent.putExtra("currentItem", position);
        intent.putExtra("dataList", urlList);
        intent.putExtra("deleteFlag", false);
        startActivityForResult(intent, ConstUtils.IMAGE_DETAIL_CODE);
    }
}
